<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="job_name" label="名称">
        <uni-easyinput placeholder="工作名称，如：维修电脑" v-model="formData.job_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="logo_picture" label="封面图片">
        <uni-file-picker return-type="object" v-model="formData.logo_picture"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="order_id" label="排序">
        <uni-easyinput placeholder="类别排序，越大越靠后" type="number" v-model="formData.order_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="parent_id" label="分类名">
        <uni-data-picker v-model="formData.parent_id" collection="familyHelper_categories" field="_id as value,name as text"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="job_price" label="价格">
        <uni-easyinput placeholder="如：30-120" v-model="formData.job_price" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="server_introduce" label="服务介绍">
          <div id="div1">
          		<div v-html="formData.introduce"></div>
          </div>
      </uni-forms-item>
      <uni-forms-item name="state" label="是否显示">
        <switch @change="binddata('state', $event.detail.value)" :checked="formData.state"></switch>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/familyHelper_list.js';
  import E from 'wangeditor'

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'familyHelper_list';
  let editor = null

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "job_name": "",
        "logo_picture": null,
        "order_id": null,
        "parent_id": "",
        "job_price": "",
        "introduce": "",
        "state": true
      }
      return {
        formData,
        formOptions: {},
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
	  this.onWangEdit()
    },
    methods: {
      onWangEdit(){
      	editor = new E('#div1')
      		editor.config.zIndex = 0		//修改编辑器的层级，不让它盖住系统提示
      		editor.config.onblur =  (newHtml) =>{
      		  	this.formData.introduce = newHtml  //将内容赋值到需要的字段
      		}
      		//在编辑器里插入图片
      		editor.config.customUploadImg = function (resultFiles, insertImgFn) {		
      			resultFiles.forEach(item=>{
      				let path = URL.createObjectURL(item)
      				let name = item.name
      				uniCloud.uploadFile({
      					filePath:path,
      					cloudPath:name
      				}).then(res=>{
      					insertImgFn(res.fileID)
      				})
      			})			
      		}
      	editor.create()
      },
	  
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
		value.introduce = editor.txt.html()
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("job_name,logo_picture,order_id,parent_id,job_price,introduce,state").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
